package com.atguigu.day09;

import com.atguigu.utils.OrderEvent;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

// 订单超时检测
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<OrderEvent> stream = env
                .addSource(new SourceFunction<OrderEvent>() {
                    @Override
                    public void run(SourceContext<OrderEvent> ctx) throws Exception {
                        OrderEvent e1 = new OrderEvent("order-1", "create", 1000L);
                        ctx.collectWithTimestamp(e1, e1.ts);
                        Thread.sleep(1000L);
                        OrderEvent e2 = new OrderEvent("order-2", "create", 2000L);
                        ctx.collectWithTimestamp(e2, e2.ts);
                        Thread.sleep(1000L);
                        OrderEvent e3 = new OrderEvent("order-1", "pay", 4000L);
                        ctx.collectWithTimestamp(e3, e3.ts);
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                });

        // 定义模板
        Pattern<OrderEvent, OrderEvent> pattern = Pattern
                .<OrderEvent>begin("create")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return value.type.equals("create");
                    }
                })
                .next("pay")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return value.type.equals("pay");
                    }
                })
                // 5秒钟之内支付
                .within(Time.seconds(5));

        PatternStream<OrderEvent> patternStream = CEP.pattern(stream.keyBy(r -> r.orderId), pattern);

        SingleOutputStreamOperator<String> result = patternStream
                .flatSelect(
                        // 超时的信息需要发送到的侧输出标签
                        new OutputTag<String>("timeout-order") {
                        },
                        // 处理超时信息的函数类
                        new PatternFlatTimeoutFunction<OrderEvent, String>() {
                            @Override
                            public void timeout(Map<String, List<OrderEvent>> pattern, long timeoutTimestamp, Collector<String> out) throws Exception {
                                OrderEvent create = pattern.get("create").get(0);
                                // 将超时信息发送到侧输出流
                                out.collect("订单：" + create.orderId + "超时未支付");
                            }
                        },
                        // 处理正常支付的信息
                        new PatternFlatSelectFunction<OrderEvent, String>() {
                            @Override
                            public void flatSelect(Map<String, List<OrderEvent>> pattern, Collector<String> out) throws Exception {
                                OrderEvent create = pattern.get("create").get(0);
                                OrderEvent pay = pattern.get("pay").get(0);
                                out.collect("订单：" + create.orderId + "创建订单的时间是：" + create.ts + "" +
                                        "支付订单的时间是：" + pay.ts);
                            }
                        }
                );

        result.print();

        result.getSideOutput(new OutputTag<String>("timeout-order"){}).print();

        env.execute();
    }
}

